<template>
  <view class="container">
    <!-- 轮播图 -->
    <swiper class="banner" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="500">
      <swiper-item v-for="(item, index) in bannerList" :key="index">
        <image :src="item.imageUrl" mode="aspectFill" class="banner-image"/>
      </swiper-item>
    </swiper>

    <!-- 公告栏 -->
    <view class="notice-bar" @click="goToPublishDetail">
      <uni-icons type="notification-filled" size="16" color="#FF6B6B"/>
      <swiper class="notice-swiper" vertical :autoplay="true" :interval="3000" :duration="500">
        <swiper-item v-for="(item, index) in noticeList" :key="index">
          <text class="notice-text">{{ item }}</text>
        </swiper-item>
      </swiper>
    </view>

    <!-- 自定义弹窗 -->
    <view v-if="showPopup" class="custom-popup-mask" @click.self="closePopup">
      <view class="custom-popup">
        <view class="custom-popup-header">
          <text class="custom-popup-title">最新公告</text>
          <text class="custom-popup-close" @click="closePopup">×</text>
        </view>
        <view class="custom-popup-body">
          <text class="custom-popup-notice-title">{{ latestNotice?.title }}</text>
          <text class="custom-popup-notice-time">{{ formatTime(latestNotice?.publishTime) }}</text>
          <scroll-view class="custom-popup-notice-content" scroll-y>
            <text>{{ latestNotice?.content }}</text>
          </scroll-view>
        </view>
        <view class="custom-popup-footer">
          <button class="custom-popup-btn" @click="goToPublishDetail">查看全部公告</button>
        </view>
      </view>
    </view>

    <!-- 功能导航 -->
    <view class="nav-grid">
      <view class="nav-item" v-for="(item, index) in navList" :key="index" @click="handleNavClick(index)">
        <image :src="item.icon" mode="aspectFit" class="nav-icon"/>
        <text class="nav-text">{{ item.title }}</text>
      </view>
    </view>

    <!-- 活动信息 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">活动推荐</text>
        <view class="more-link" @click="goToActivityList">
          <text class="more-text">更多活动</text>
          <uni-icons type="right" size="14" color="#666666"/>
        </view>
      </view>
      <view class="activity-list">
        <view class="activity-item" v-for="item in recommendActivityList" :key="item.id" @click="goToActivityDetail(item.id)">
          <image :src="item.image_url" mode="aspectFill" class="activity-image"/>
          <view class="activity-content">
            <text class="activity-title">{{ item.title }}</text>
            <text class="activity-desc">{{ item.content }}</text>
            <view class="activity-status">
              <text class="status-text">{{ item.capacity }}人</text>
              <text class="status-text">{{ item.points }}积分</text>
              <text class="status-text">{{ item.location }}</text>
            </view>
          </view>
        </view>
        <view v-if="recommendActivityList.length === 0" class="no-activity">暂无推荐活动</view>
      </view>
    </view>

    <!-- 新闻资讯 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">新闻资讯</text>
      </view>
      <scroll-view class="category-scroll" scroll-x>
        <view class="category-list">
          <view 
            class="category-item" 
            v-for="item in newsCategories" 
            :key="item.id"
            :class="{'category-active': currentCategoryId === item.id}"
            @tap="changeCategory(item.id)"
          >
            {{ item.name }}
          </view>
        </view>
      </scroll-view>
      <view class="news-list">
        <view class="news-item" v-for="item in newsList" :key="item.id" @click="goToNewsDetail(item.id)">
          <image :src="item.cover_url" mode="aspectFill" class="news-image"/>
          <view class="news-content">
            <text class="news-title">{{ item.title }}</text>
            <text class="news-desc">{{ item.content }}</text>
          </view>
        </view>
        <view v-if="newsList.length === 0" class="no-news">暂无新闻</view>
        <!-- 底部安全区占位，防止tabBar遮挡内容 -->
        <view style="height: 120rpx;"></view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { request } from '../../utiles/request';

const bannerList = ref([]);
const noticeList = ref([]);
const latestNotice = ref(null);
const showPopup = ref(false);

// 新闻分类与新闻列表
const newsCategories = ref<{id:number, name:string}[]>([]);
const currentCategoryId = ref<number|null>(null);
const newsList = ref<any[]>([]);

// 推荐活动列表
const recommendActivityList = ref<any[]>([]);

// 获取轮播图数据
const getBannerList = () => {
  request({
    url: '/admin/api/carousel/list',
    method: 'GET'
  }).then(res => {
    if (res.data && res.data.code === 200) {
      bannerList.value = res.data.data;
    } else {
      uni.showToast({
        title: res.data?.msg || '获取轮播图失败',
        icon: 'none'
      });
    }
  }).catch(() => {
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    });
  });
};

// 获取公告列表
const getNoticeList = () => {
  request({
    url: '/admin/api/notice/list',
    method: 'GET',
    data: {
      page: 1,
      pageSize: 3
    }
  }).then(res => {
    if (res.data && res.data.code === 200) {
      noticeList.value = res.data.data.list.map(item => item.title);
    } else {
      uni.showToast({
        title: res.data?.msg || '获取公告失败',
        icon: 'none'
      });
    }
  }).catch(() => {
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    });
  });
};

// 获取最新公告并显示弹窗
const getLatestNotice = () => {
  request({
    url: '/admin/api/notice/list',
    method: 'GET',
    data: {
      page: 1,
      pageSize: 1
    }
  }).then(res => {
    if (res.data && res.data.code === 200 && res.data.data.list.length > 0) {
      latestNotice.value = res.data.data.list[0];
      showPopup.value = true;
    }
  });
};

const closePopup = () => {
  showPopup.value = false;
};

// 跳转到公告详情页
const goToPublishDetail = () => {
  showPopup.value = false;
  uni.navigateTo({
    url: '/pages/publishDetail/publishDetail'
  });
};

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return '';
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}`;
};

onMounted(() => {
  getBannerList();
  getNoticeList();
  getLatestNotice();
  getNewsCategories();
  getRecommendActivity();
});

const navList = ref([
  {
    title: '组织介绍',
    icon: 'https://ai-public.mastergo.com/ai/img_res/75adeea196c94709747a82c24759b7ad.jpg'
  },
  {
    title: '新闻咨询',
    icon: 'https://ai-public.mastergo.com/ai/img_res/91783d9cb89c5444bd74e8032597f747.jpg'
  },
  {
    title: '活动报名',
    icon: 'https://ai-public.mastergo.com/ai/img_res/ccafe10aa8cae9d79885dc438302f120.jpg'
  },
  {
    title: '积分排行',
    icon: 'https://ai-public.mastergo.com/ai/img_res/c9977bd887671392bf896684cf881560.jpg'
  }
]);

// 获取新闻分类
const getNewsCategories = () => {
  request({
    url: '/admin/api/newsclass/list',
    method: 'GET'
  }).then(res => {
    if (res.data && res.data.code === 200) {
      newsCategories.value = res.data.data;
      // 默认选中第一个分类
      if (newsCategories.value.length > 0) {
        currentCategoryId.value = newsCategories.value[0].id;
        getNewsList();
      }
    }
  });
};

// 获取新闻列表
const getNewsList = () => {
  request({
    url: '/admin/api/news/list',
    method: 'GET',
    data: {
      category_id: currentCategoryId.value
    }
  }).then(res => {
    if (res.data && res.data.code === 200) {
      newsList.value = res.data.data;
    }
  });
};

// 切换分类
const changeCategory = (id: number) => {
  currentCategoryId.value = id;
  getNewsList();
};

// 跳转到新闻详情页
const goToNewsDetail = (id: number) => {
  uni.navigateTo({
    url: `/pages/newsDetail/newsDetail?id=${id}`
  });
};

// 组织介绍跳转
const handleNavClick = (index: number) => {
  if (index === 0) {
    uni.navigateTo({
      url: '/pages/introduce/introduce'
    });
  } else if (index === 1) {
    uni.navigateTo({
      url: '/pages/newlists/newlists'
    });
  } else if (index === 2) {
    uni.navigateTo({
      url: '/pages/activetyList/activetyList'
    });
  } else if (index === 3) {
    uni.navigateTo({
      url: '/pages/myrecord/myrecord'
    });
  }
  // 其他导航项可按需扩展
};

// 获取推荐活动
const getRecommendActivity = () => {
  // 获取用户ID
  let userId = null;
  const local = uni.getStorageSync('userInfo');
  if (local) {
    try {
      const obj = typeof local === 'string' ? JSON.parse(local) : local;
      userId = obj.data?.id || obj.id;
    } catch (e) {
      userId = null;
    }
  }
  if (!userId) return;
  request({
    url: '/admin/api/activity/recommend',
    method: 'GET',
    data: { user_id: userId }
  }).then(res => {
    if (res.data && (res.data.code === 0 || res.data.code === 200)) {
      recommendActivityList.value = res.data.data.list;
    }
  });
};

const goToActivityList = () => {
  uni.navigateTo({
    url: '/pages/activetyList/activetyList'
  });
};

// 跳转到活动详情页
const goToActivityDetail = (id: number) => {
  uni.navigateTo({
    url: `/pages/activetyDetail/activetyDetail?id=${id}`
  });
};
</script>

<style>
page {
  height: 100%;
  background-color: #F5F5F5;
}

.container {
  min-height: 100%;
  background-color: #F5F5F5;
}

.banner {
  width: 750rpx;
  height: 400rpx;
}

.banner-image {
  width: 750rpx;
  height: 400rpx;
}

.notice-bar {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #FFFFFF;
  margin: 20rpx 0;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.notice-bar:active {
  transform: scale(0.98);
  opacity: 0.9;
}

.notice-swiper {
  height: 40rpx;
  flex: 1;
  margin-left: 20rpx;
}

.notice-text {
  font-size: 14px;
  color: #333333;
  line-height: 40rpx;
}

.nav-grid {
  display: flex;
  justify-content: space-between;
  padding: 30rpx;
  background-color: #FFFFFF;
  margin-bottom: 20rpx;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 140rpx;
}

.nav-icon {
  width: 100rpx;
  height: 100rpx;
  margin-bottom: 16rpx;
}

.nav-text {
  font-size: 14px;
  color: #333333;
}

.section {
  background-color: #FFFFFF;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333333;
}

.more-link {
  display: flex;
  align-items: center;
}

.more-text {
  font-size: 14px;
  color: #666666;
  margin-right: 4rpx;
}

.activity-list {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.activity-item {
  display: flex;
  gap: 18rpx;
  background: #fff;
  border-radius: 18rpx;
  box-shadow: 0 4rpx 18rpx rgba(25, 118, 210, 0.07);
  padding: 20rpx 24rpx;
  margin-bottom: 18rpx;
  align-items: center;
  min-height: 120rpx;
}

.activity-image {
  width: 110rpx;
  height: 82rpx;
  border-radius: 12rpx;
  margin-right: 0;
  flex-shrink: 0;
  object-fit: cover;
  background: #f5f7fa;
}

.activity-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-width: 0;
}

.activity-title {
  font-size: 30rpx;
  color: #222;
  font-weight: bold;
  margin-bottom: 6rpx;
  line-height: 1.2;
}

.activity-desc {
  font-size: 22rpx;
  color: #999;
  margin-bottom: 10rpx;
  line-height: 1.4;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

.activity-status {
  display: flex;
  gap: 22rpx;
  font-size: 22rpx;
  margin-top: 2rpx;
}

.activity-status .status-text {
  color: #e53935;
  font-weight: 500;
}

.activity-status .status-text:nth-child(2) {
  color: #1976D2;
  font-weight: 400;
}

.activity-status .status-text:nth-child(3) {
  color: #43a047;
  font-weight: 400;
}

.category-scroll {
  margin: 0 -30rpx;
  padding: 0 30rpx;
  white-space: nowrap;
  margin-bottom: 30rpx;
}

.category-list {
  display: inline-flex;
  gap: 30rpx;
}

.category-item {
  padding: 10rpx 30rpx;
  font-size: 14px;
  color: #666666;
  background-color: #F5F5F5;
  border-radius: 30rpx;
}

.category-active {
  color: #FFFFFF;
  background-color: #FF6B6B;
}

.news-list {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.news-item {
  display: flex;
  gap: 20rpx;
}

.news-image {
  width: 200rpx;
  height: 150rpx;
  border-radius: 8rpx;
}

.news-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.news-title {
  font-size: 16px;
  color: #333333;
  margin-bottom: 10rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.news-desc {
  font-size: 14px;
  color: #666666;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.center {
  justify-content: center;
  padding-top: 20rpx;
}

/* 弹窗样式 */
.custom-popup-mask {
  position: fixed;
  z-index: 9999;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.35);
  display: flex;
  align-items: center;
  justify-content: center;
}
.custom-popup {
  width: 600rpx;
  background: #fff;
  border-radius: 24rpx;
  box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.18);
  overflow: hidden;
  animation: popup-fade-in 0.3s;
  display: flex;
  flex-direction: column;
}
@keyframes popup-fade-in {
  from { transform: scale(0.9); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}
.custom-popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx 32rpx 0 32rpx;
}
.custom-popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #1976D2;
}
.custom-popup-close {
  font-size: 40rpx;
  color: #999;
  cursor: pointer;
  font-weight: bold;
  line-height: 1;
}
.custom-popup-body {
  padding: 24rpx 32rpx 0 32rpx;
  flex: 1;
}
.custom-popup-notice-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #222;
  margin-bottom: 8rpx;
  display: block;
}
.custom-popup-notice-time {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 16rpx;
  display: block;
}
.custom-popup-notice-content {
  max-height: 240rpx;
  font-size: 28rpx;
  color: #444;
  line-height: 1.7;
  margin-bottom: 16rpx;
  white-space: pre-wrap;
}
.custom-popup-footer {
  padding: 24rpx 32rpx 32rpx 32rpx;
}
.custom-popup-btn {
  width: 100%;
  height: 80rpx;
  background: linear-gradient(135deg, #1976D2 0%, #1565C0 100%);
  border-radius: 40rpx;
  color: #fff;
  font-size: 28rpx;
  font-weight: 500;
  border: none;
}
.custom-popup-btn:active {
  opacity: 0.9;
}
</style>

